import { Drawer, Input, InputNumber, message } from 'antd';
import Button from 'antd/es/button';
import { FormInstance } from 'antd/lib/form';
import Form from 'antd/lib/form/Form';
import FormItem from 'antd/lib/form/FormItem';
import { FetchDataParam, FetchDataResponse, PageSelect } from 'components/UILibrary/pageSelect';
import React from 'react';
import { CorporateInfo } from '../../../../schema/Corporate';
import { createCorporate, getIndustryList, modifyCorporate } from '../../../../servers/servers';
import {
  clearNull,
  encryptStr,
  verifyAccount,
  verifyAccountPwd,
  verifyNull,
  verifyPhone,
  verifySeatsNumber,
} from '../../../../../utils/tools';

const { TextArea } = Input;

/**
 * 企业操作入参
 */
interface OperationOption {
  /**提交函数结束后的回调,编辑需要传obj，判断是否跳第一页 */
  callback: (obj?: any) => any;
}

/**
 * 企业操作维护的state
 */
interface OperationState extends OperationOption {
  // 当前的操作类型为新增还是编辑
  mode: 'create' | 'modify';
  // 当前操作弹出抽屉的可见性
  visible: boolean;
}

/**
 * 企业管理操作
 */
export class CorporateOperationDrawer extends React.Component<OperationOption, OperationState> {
  // 表单引用
  private formRef: React.RefObject<FormInstance>;

  // 行业选择器引用
  private industryRef: React.RefObject<PageSelect>;

  // 当前的企业信息
  private corporateInfo?: CorporateInfo;

  constructor(props: OperationOption) {
    super(props);
    this.formRef = React.createRef<FormInstance>();
    this.industryRef = React.createRef<PageSelect>();
    this.state = {
      ...props,
      mode: 'create',
      visible: false,
    };
  }

  /**
   * 展开抽屉并设置类型
   */
  public open(mode: 'create' | 'modify'): void {
    this.setState({
      visible: true,
      mode: mode,
    });
  }

  /**
   * 关闭抽屉
   */
  public close(): void {
    this.formRef.current?.resetFields();
    this.setState({
      visible: false,
    });
  }

  /**
   * 设置表单值
   */
  public setValue(val: CorporateInfo): void {
    setTimeout(() => {
      this.corporateInfo = val;
      this.formRef.current?.setFieldsValue(val);
      this.industryRef.current?.setValueWithoutPage(val.industryName, true);
    }, 0);
  }

  /**
   * 提交 新增/编辑 的数据
   */
  private submitData(): void {
    const form = this.formRef.current;
    const callback = this.state.callback;
    form?.validateFields().then(res => {
      const val = form.getFieldsValue() as CorporateInfo;
      val.companyName = val.companyName.replace(/ /g, '');
      val.pwd = encryptStr(val.pwd);
      if (this.state.mode === 'create') {
        createCorporate(val)
          .then(res => {
            message.success('创建成功');
            callback();
            this.close();
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      } else {
        const corporateId = this.corporateInfo?.companyId as number;
        modifyCorporate(corporateId, val)
          .then(res => {
            message.success('修改成功');
            callback(corporateId);
            this.close();
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      }
    });
  }

  /**
   * 渲染抽屉底部footer
   */
  private buildFooter(): JSX.Element {
    return (
      <div className="drawer-footer-buttongroup">
        <Button
          type="primary"
          onClick={() => {
            this.submitData();
          }}
        >
          确定
        </Button>
        <Button
          onClick={() => {
            this.close();
          }}
        >
          取消
        </Button>
      </div>
    );
  }

  private fetchIndustry(arg: FetchDataParam): FetchDataResponse {
    return new Promise(resolve => {
      getIndustryList(
        clearNull({
          pageNo: arg.pageNum,
          pageSize: arg.pageSize,
          industryName: arg.keywords,
        })
      )
        .then(res => {
          if (!res.data) {
            resolve({
              total: 1,
              data: [],
            });
          }
          resolve({
            total: res.count || 10,
            data: res.data.map(item => {
              return {
                label: item.industryName,
                value: item.industryId,
              };
            }),
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }

  render() {
    const { visible, mode } = this.state;
    const { industryRef } = this;
    const layout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    };

    return (
      <>
        {visible && (
          <Drawer
            className="corporate-operation-drawer"
            width={620}
            visible={true}
            title={mode === 'create' ? '新建企业' : '编辑企业'}
            onClose={() => {
              this.close();
            }}
            footer={this.buildFooter()}
          >
            <Form {...layout} layout="horizontal" ref={this.formRef}>
              <FormItem
                label="企业名称"
                name="companyName"
                rules={verifyNull()}
                getValueFromEvent={event => {
                  return event.target.value.replace(/\s+/g, '');
                }}
              >
                <Input maxLength={30} placeholder="请输入30位内字符" />
              </FormItem>
              <FormItem label="所选行业" name="industryId" rules={verifyNull('请选择行业')}>
                <PageSelect
                  allowClear
                  ref={industryRef}
                  pageSize={10000}
                  fetchData={this.fetchIndustry}
                  placeholder="请选择所选行业"
                />
              </FormItem>
              <FormItem
                label="联系人姓名"
                name="contactName"
                rules={verifyNull()}
                getValueFromEvent={event => {
                  return event.target.value.replace(/\s+/g, '');
                }}
              >
                <Input maxLength={15} placeholder="请输入15位内字符" />
              </FormItem>
              <FormItem
                label="手机号"
                name="contactNumber"
                rules={verifyPhone}
                validateFirst={true}
                getValueFromEvent={event => {
                  return event.target.value.replace(/\s+/g, '');
                }}
              >
                <Input maxLength={11} placeholder="请输入11位数字" />
              </FormItem>
              <FormItem label="纳税人识别号" name="taxpayerIdentityNumber">
                <Input placeholder="请输入纳税人识别号" maxLength={20} />
              </FormItem>
              {mode === 'create' && (
                <>
                  <FormItem label="企业账号" name="account" rules={verifyAccount}>
                    <Input maxLength={15} placeholder="请输入15位内字符" />
                  </FormItem>
                  <FormItem
                    label="密码"
                    name="pwd"
                    rules={verifyAccountPwd}
                    validateFirst={true}
                    getValueFromEvent={event => {
                      // 圆点符号包含逗号，所以过滤逗号需单独处理
                      return event.target.value
                        .replace(/,+/g, '')
                        .replace(/[^a-zA-Z0-9~@#\$*%\^:;_.+-\/]+/g, '')
                        .slice(0, 30);
                    }}
                  >
                    <Input
                      minLength={8}
                      maxLength={30}
                      placeholder="8位以上字符，需包含大写字母、小写字母、数字和特殊字符中的三类"
                    />
                  </FormItem>
                </>
              )}
              <FormItem label="最大任务并发" name="maxTask" rules={verifyNull()}>
                <InputNumber placeholder="请输入数字" precision={0} min={1} max={99999999} />
              </FormItem>
              <FormItem label="最大呼叫并发" name="maxCall" rules={verifyNull()}>
                <InputNumber placeholder="请输入数字" precision={0} min={1} max={99999999} />
              </FormItem>
              {mode === 'create' && (
                <FormItem
                  label="坐席工号"
                  name="seatsNum"
                  rules={verifySeatsNumber}
                  validateFirst={true}
                  getValueFromEvent={event => {
                    return event.target.value.replace(/[^0-9]+/g, '');
                  }}
                >
                  <Input minLength={6} maxLength={6} placeholder="请输入6位数字" />
                </FormItem>
              )}
              <FormItem label="企业地址" name="companyAddress">
                <TextArea placeholder="企业地址" />
              </FormItem>
            </Form>
          </Drawer>
        )}
      </>
    );
  }
}
